import user from "@/api/modules/user";
import store from "@/store";
const state = {
  data: []
};

const actions = {
  // 获取省
  getProvince(context) {
    if (store.state.address.data.length <= 0) {
      return user.getCity(0).then(response => {
        let provice = response.data.data.map(item => {
          item['child'] = [];
          return item;
        });
        context.commit("SET_DATA", provice);
        return provice;
      });
    }
    return Promise.resolve(store.state.address.data);
  },
  /**
   * @param {Object} context
   * @param {Object} opt {pindex}
   */
  getCity(context, opt) {
    let data = store.state.address.data;
    if (data[opt.pindex].child.length <= 0) {
      return user.getCity(data[opt.pindex].id).then(response => {
        let city = response.data.data.map(item => {
          item['child'] = [];
          return item;
        })
        data[opt.pindex].child = city;
        context.commit("SET_DATA", data);
        return response.data.data;
      });
    } else {
      return Promise.resolve(data[opt.pindex].child);
    }
  },
  /**
   * 获取区
   * @param {Object} context
   * @param {Object} opt {pindex,cindex}
   */
  getRegion(context, opt) {
    let data = store.state.address.data;
    let city = data[opt.pindex].child;
    if (city[opt.cindex].child.length <= 0) {
      return user.getCity(city[opt.cindex].id).then(response => {
        data[opt.pindex].child[opt.cindex].child = response.data.data;
        context.commit("SET_DATA", data);
        return response.data.data;
      });
    } else {
      return Promise.resolve(city[opt.cindex].child);
    }
  },

};

const mutations = {
  SET_DATA(state, data) {
    state.data = data;
  }
};


export default {
  namespaced: true,
  state,
  actions,
  mutations
};
